package cn.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @auth wzy
 * @date 2023/9/27 15:32
 */
public class Test2 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse("resources/phone.xml");

        Element brandSamsung = doc.createElement("brand");
        brandSamsung.setAttribute("name","三星");

        Element typeSamsung = doc.createElement("type");
        typeSamsung.setAttribute("name","S22");

        brandSamsung.appendChild(typeSamsung);



        Node phoneInfo = doc.getElementsByTagName("phoneInfo").item(0);
        phoneInfo.appendChild(brandSamsung);

        // 保存xml文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        DOMSource domSource = new DOMSource(doc);

        StreamResult streamResult = new StreamResult(new FileOutputStream("resources/phone1.xml"));

        transformer.transform(domSource, streamResult);

    }
}
